<?php
/*
本系统由苏酷伊基于SiteHub项目二次开发
作者博客： https://www.sukuy.com/
后续更新地址： https://www.sukuy.com/navigation
作者QQ：3288637559
QQ交流群：884250547
任何第三方非官网在发布本系统时，不得删除该注释、版权信息、作者信息及官网等内容
*/
if (!isset($_GET['url'])) {
    return http_response_code(404);
}
define('ROOT', dirname(__FILE__));

require ROOT . '/includes/favicon.class.php';
define('CACHE_ROOT', ROOT . '/cache/favicon'); 
$defaultIco = ROOT . '/assets/images/default_ico.png'; 
$expire = 2592000; 
$favicon = new Favicon;
$favicon->setDefaultIcon($defaultIco);
$url = $_GET['url'];
$url = trim(htmlspecialchars($url));
$formatUrl = $favicon->formatUrl($url);
if ($expire == 0) {
    $favicon->getFavicon($formatUrl, false);
    @header("Cache-Control: public, max-age={$expire}");
    @header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    exit;
} else {
    $defaultMD5 = md5(file_get_contents($defaultIco));
    $data = Cache::get($formatUrl, $defaultMD5, $expire);
    if ($data !== NULL) {
        foreach ($favicon->getHeader() as $header) {
            @header($header);
        }
        @header("Cache-Control: public, max-age={$expire}");
        
        $file = CACHE_ROOT . '/' . parse_url($formatUrl)['host'] . '.txt';
        @header("Last-Modified: " . gmdate("D, d M Y H:i:s", filemtime($file)) . " GMT");
        echo $data;
        exit;
    }
    $content = $favicon->getFavicon($formatUrl, TRUE);
    if (md5($content) == $defaultMD5) {
        $expire = 43200; 
    }
    Cache::set($formatUrl, $content, $expire);

    foreach ($favicon->getHeader() as $header) {
        @header($header);
    }
    @header("Cache-Control: public, max-age={$expire}");
    @header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    echo $content;
    exit;
}
class Cache
{
    public static function get($key, $default, $expire)
    {
        $f = parse_url($key)['host'];

        $file = CACHE_ROOT . '/' . $f . '.txt';

        if (is_file($file)) {
            $data = file_get_contents($file);
            if (md5($data) == $default) {
                $expire = 43200; 
            }
            if ((time() - filemtime($file)) > $expire) {
                return null;
            } else {
                return $data;
            }
        } else {
            return null;
        }
    }
    public static function set($key, $value, $expire)
    {
        $f = parse_url($key)['host'];

        $file = CACHE_ROOT . '/' . $f . '.txt';
        if (!is_dir(CACHE_ROOT)) mkdir(CACHE_ROOT, 0777, true) or die('创建缓存目录失败！');

        if (!is_file($file) || (time() - filemtime($file)) > $expire) {
            $imgdata = fopen($file, "w") or die("Unable to open file!");  
            fwrite($imgdata, $value);
            fclose($imgdata);
        }
    }
}